<template>
    <div class="flex-home">
        <a-layout style="height: 100vh;">
            <TopHeader
                :user-info="userInfo"
                @logout="logout"
                @show-user-info="showUserInfo"
                @switch-user="switchUser"
            />
            <a-layout>
                <!-- Resizable Left Sider -->
                <a-layout-sider 
                    :width="siderCollapsed ? 0 : siderWidth" 
                    class="sider"
                    :class="{ 'sider-collapsed': siderCollapsed }"
                >
                    <div class="sider-content">
                        <div class="sider-header">
                            <span>分组列表</span>
                            <a-button
                                type="link"
                                :icon="areAllGroupsExpanded ? 'menu-fold' : 'menu-unfold'"
                                size="small"
                                :title="areAllGroupsExpanded ? '全部折叠' : '全部展开'"
                                @click="toggleGroupTreeExpansion"
                            />
                        </div>
                        <GroupTree
                            ref="groupTree"
                            @select="onNodeSelect"
                        />
                    </div>
                    <div class="sider-resizer" @mousedown="handleMouseDown" />
                </a-layout-sider>

                <!-- Floating Toggle Button -->
                <div 
                    class="sider-toggle-btn"
                    :class="{ 'toggle-btn-collapsed': siderCollapsed }"
                    :style="{ left: siderCollapsed ? '0px' : (siderWidth - 20 + 'px') }"
                    :title="siderCollapsed ? '展开分组' : '收起分组'"
                    @click="toggleSider"
                >
                    <a-icon :type="siderCollapsed ? 'double-right' : 'double-left'" />
                </div>

                <!-- Right Content -->
                <a-layout>
                    <a-layout-header class="main-header">
                        <div class="header-content">
                            <div class="custom-tab-header">
                                <div class="icons-row">
                                    <div
                                        v-for="tab in mainTabs"
                                        :key="tab.key"
                                        class="icon-item"
                                        @click="activeTab = tab.key"
                                    >
                                        <a-icon :type="tab.icon" :class="{ active: activeTab === tab.key }" />
                                    </div>
                                </div>
                                <div class="titles-row">
                                    <div
                                        v-for="tab in mainTabs"
                                        :key="tab.key"
                                        class="title-item"
                                        @click="activeTab = tab.key"
                                    >
                                        <span :class="{ active: activeTab === tab.key }">{{ tab.title }}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </a-layout-header>
                    <a-layout-content class="main-content">
                        <keep-alive>
                            <component
                                :is="activeTabComponent"
                                :selected-key="selectedKey"
                                @edit="onEditFromTab"
                                @delete="onDeleteFromTab"
                                @updateDeviceStatus="onUpdateDeviceStatus"
                                @revertDeviceSelection="onRevertDeviceSelection"
                            />
                        </keep-alive>
                    </a-layout-content>
                </a-layout>
            </a-layout>
        </a-layout>

        <!-- Modals -->
        <a-modal v-model="userInfoVisible" title="用户信息" :footer="null">
            <p>用户名：{{ userInfo.username }}</p>
            <p>登录时间：{{ userInfo.loginTime }}</p>
            <p>Token：{{ userInfo.token }}</p>
        </a-modal>
    </div>
</template>

<script>
import GroupTree from '@/components/GroupTree.vue'
import TopHeader from '@/components/TopHeader.vue'
// Import Tab Components
import MonitorTab from './tabs/MonitorTab.vue'
import HistoryTab from './tabs/HistoryTab.vue'
import EdgeTab from './tabs/EdgeTab.vue'
import ToolsTab from './tabs/ToolsTab.vue'
import DeviceTab from './tabs/DeviceTab.vue'
import SettingsTab from './tabs/SettingsTab.vue'
// import AlarmTab from './tabs/AlarmTab.vue'
// import DownloadTab from './tabs/DownloadTab.vue'

export default {
    components: {
        GroupTree,
        TopHeader,
        MonitorTab,
        HistoryTab,
        EdgeTab,
        ToolsTab,
        DeviceTab,
        SettingsTab
        // AlarmTab,
        // DownloadTab,
    },
    data() {
        return {
            siderWidth: 350,
            selectedKey: 'default', // Only need to keep track of the selected key
            activeTab: 'monitor',
            mainTabs: [
                { key: 'monitor', title: '数据监控', icon: 'dashboard', component: 'MonitorTab' },
                { key: 'settings', title: '基本配置', icon: 'setting', component: 'SettingsTab' },
                { key: 'edge', title: '脚本编程', icon: 'code', component: 'EdgeTab' },
                { key: 'device', title: '设备操作', icon: 'tool', component: 'DeviceTab' },
                { key: 'history', title: '历史数据', icon: 'history', component: 'HistoryTab' },
                { key: 'tools', title: '辅助工具', icon: 'api', component: 'ToolsTab' }
                // { key: 'download', title: '远程下载', icon: 'download', component: 'DownloadTab' },
                // { key: 'alarm', title: '报警记录', icon: 'calendar', component: 'AlarmTab' }
            ],
            userInfoVisible: false,
            userInfo: {
                username: 'admin',
                loginTime: new Date().toLocaleString(),
                token: (this.$store && this.$store.state && this.$store.state.token && this.$store.state.token.token) || '未获取到Token'
            },
            // This state is now managed by GroupTree, but we need a local copy for the button icon.
            areAllGroupsExpanded: true,
            siderCollapsed: false // New state for sider collapse
        }
    },
    computed: {
        activeTabComponent() {
            const active = this.mainTabs.find(tab => tab.key === this.activeTab)
            return active ? active.component : null
        }
    },
    methods: {
        // --- Communication with GroupTree ---
        onNodeSelect(key) {
            this.selectedKey = key
        },
        toggleGroupTreeExpansion() {
            // Call public method on child component
            if (this.$refs.groupTree && typeof this.$refs.groupTree.toggleGroupExpansion === 'function') {
                this.$refs.groupTree.toggleGroupExpansion()
            }
            // Update local state for the icon
            this.areAllGroupsExpanded = !this.areAllGroupsExpanded
        },
        onEditFromTab(key) {
            if (this.$refs.groupTree && typeof this.$refs.groupTree.showEditModal === 'function') {
                this.$refs.groupTree.showEditModal(key)
            }
        },
        onDeleteFromTab(key) {
            if (this.$refs.groupTree && typeof this.$refs.groupTree.confirmDelete === 'function') {
                this.$refs.groupTree.confirmDelete(key)
            }
        },

        // --- Sider Resize ---
        handleMouseDown(e) {
            e.preventDefault()
            document.body.style.cursor = 'col-resize'
            window.addEventListener('mousemove', this.handleMouseMove)
            window.addEventListener('mouseup', this.handleMouseUp)
        },
        handleMouseMove(e) {
            let newWidth = e.clientX
            if (newWidth < 200) newWidth = 200
            if (newWidth > 600) newWidth = 600
            this.siderWidth = newWidth
        },
        handleMouseUp() {
            document.body.style.cursor = ''
            window.removeEventListener('mousemove', this.handleMouseMove)
            window.removeEventListener('mouseup', this.handleMouseUp)
        },

        // --- Sider Collapse/Expand ---
        toggleSider() {
            this.siderCollapsed = !this.siderCollapsed
            if (this.siderCollapsed) {
                this.siderWidth = 0 // Collapse to 0 width
            } else {
                this.siderWidth = 350 // Expand to original width
            }
        },

        // --- User Actions ---
        showUserInfo() {
            this.userInfoVisible = true
        },
        switchUser() {
            this.$message.info('切换用户功能开发中')
        },
        logout() {
            localStorage.removeItem('token')
            localStorage.removeItem('failuretime')
            this.$store.commit('token/setData', { token: null, failuretime: null })
            this.$message.success('已退出登录')
            this.$router.replace('/login')
        },
        onUpdateDeviceStatus(statusInfo) {
            console.log('📨 [Index] 接收到设备状态更新事件:', statusInfo)
            console.log('🔍 [Index] GroupTree 引用:', this.$refs.groupTree)
            
            if (this.$refs.groupTree) {
                if (typeof this.$refs.groupTree.updateDeviceStatus === 'function') {
                    console.log('📤 [Index] 调用 GroupTree.updateDeviceStatus')
                    this.$refs.groupTree.updateDeviceStatus(statusInfo)
                } else {
                    console.error('🚨 [Index] GroupTree.updateDeviceStatus 方法不存在')
                }
            } else {
                console.error('🚨 [Index] GroupTree 引用不存在')
            }
        },
        onRevertDeviceSelection(device) {
            console.log('🔄 [Index] 接收到设备选择恢复请求:', device)
            
            try {
                // 直接通过Vuex恢复设备选择状态
                this.$store.commit('groupTree/SET_SELECTED_DEVICE', device)
                console.log('✅ [Index] 通过Vuex恢复设备选择成功')
                
                // 同时通知GroupTree组件更新UI状态
                if (this.$refs.groupTree) {
                    // 使用$nextTick确保Vuex状态更新后再更新UI
                    this.$nextTick(() => {
                        if (typeof this.$refs.groupTree.selectDevice === 'function') {
                            console.log('📤 [Index] 调用 GroupTree.selectDevice 恢复UI状态')
                            this.$refs.groupTree.selectDevice(device.key, device)
                        } else {
                            // 如果selectDevice方法不可用，尝试直接更新selectedKeys
                            console.log('📤 [Index] 直接更新 GroupTree selectedKeys')
                            this.$refs.groupTree.selectedKeys = [device.key]
                            
                            // 查找设备的真实父分组
                            const parentGroup = this.findParentGroupForDevice(device.key)
                            if (parentGroup && !this.$refs.groupTree.expandedKeys.includes(parentGroup)) {
                                console.log('📤 [Index] 展开父分组:', parentGroup)
                                this.$refs.groupTree.expandedKeys = [...this.$refs.groupTree.expandedKeys, parentGroup]
                            }
                        }
                    })
                } else {
                    console.error('🚨 [Index] GroupTree 引用不存在')
                }
            } catch (error) {
                console.error('❌ [Index] 设备选择恢复失败:', error)
                this.$message.error('设备选择恢复失败')
            }
        },
        
        // 查找设备的父分组
        findParentGroupForDevice(deviceKey) {
            if (!this.$refs.groupTree || !this.$refs.groupTree.treeData) {
                return null
            }
            
            const treeData = this.$refs.groupTree.treeData
            for (const group of treeData) {
                if (group.children) {
                    for (const device of group.children) {
                        if (device.key === deviceKey) {
                            return group.key
                        }
                    }
                }
            }
            return null
        }
    }
}
</script>

<style scoped>
.flex-home {
    height: 100vh;
}
.sider {
    background: #fff;
    border-right: 1px solid #eee;
    position: relative; /* Needed for the resizer and toggle button */
    display: flex;
    flex-direction: column;
    transition: width 0.3s ease-in-out; /* Add transition for sider width */
}
.sider-collapsed {
    width: 0 !important; /* Override width when collapsed */
    overflow: hidden; /* Hide content when collapsed */
    opacity: 0; /* Fade out content */
}
.sider-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0;
    height: 100%;
}
.sider-resizer {
    position: absolute;
    top: 0;
    right: -3px;
    width: 6px;
    height: 100%;
    cursor: col-resize;
    z-index: 99;
}
.sider-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-shrink: 0;
    padding: 8px 12px;
    font-weight: bold;
    border-bottom: 1px solid #f0f0f0;
}
.sider-toggle-btn {
    position: fixed;
    top: 50%;
    transform: translateY(-50%);
    width: 40px;
    height: 40px;
    background-color: #1890ff;
    color: #fff;
    border-radius: 50%; /* 改回圆形 */
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    z-index: 100;
    transition: all 0.3s ease-in-out;
}
.sider-toggle-btn:hover {
    background-color: #40a9ff;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}
.sider-toggle-btn .anticon {
    font-size: 16px;
}
.main-header {
    background: #fff;
    padding: 0;
    height: auto;
    line-height: initial;
}
.header-content {
    display: flex;
    padding: 0;
}

/* New Custom Tab Styles */
.custom-tab-header {
    width: 100%;
    padding: 8px 0;
    border-bottom: 1px solid #eee;
}
.icons-row,
.titles-row {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    gap: 20px;
    max-width: 900px;
    padding-left: 20px;
}
.icons-row {
    margin-bottom: 8px;
}
.icon-item,
.title-item {
    cursor: pointer;
    text-align: center;
    min-width: 80px;
    max-width: 120px;
    flex: 0 0 auto;
}
.icon-item .anticon {
    font-size: 28px;
    color: #595959;
    transition: color 0.3s;
}
.icon-item .anticon.active {
    color: #1890ff;
}
.title-item span {
    font-size: 14px;
    color: #595959;
    position: relative;
    padding-bottom: 8px;
    transition: color 0.3s;
}
.title-item span.active {
    color: #1890ff;
}
.title-item span.active::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 2px;
    background-color: #1890ff;
    border-radius: 1px;
}
.main-content {
    padding: 16px;
    background: #f5f7fa;
    min-height: 0;
    overflow-y: auto;
}
.table-actions {
    margin-top: 16px;
    display: flex;
    gap: 8px;
}
.manage-groups-content {
    padding: 16px;
}
.manage-groups-header {
    margin-bottom: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 12px;
    border-bottom: 1px solid #f0f0f0;
}
.selected-count {
    color: #666;
    font-size: 14px;
}
.groups-list {
    max-height: 300px;
    overflow-y: auto;
}
.groups-list .ant-list-item {
    padding: 12px 0;
    border-bottom: 1px solid #f5f5f5;
}
.groups-list .ant-list-item:last-child {
    border-bottom: none;
}
.groups-list .ant-checkbox-wrapper {
    margin-right: 12px;
}
.default-group-tag {
    color: #999;
    font-size: 12px;
    background: #f5f5f5;
    padding: 2px 6px;
    border-radius: 3px;
}
.group-tree {
    height: 100%;
    display: flex;
    flex-direction: column;
}
.tree-wrapper {
    flex: 1;
    min-height: 0;
    overflow: auto;
    padding: 16px;
    border-right: 1px solid #e8e8e8;

    /* 保证树内容撑满剩余空间并可滚动 */
}
.group-tree-actions {
    padding: 16px;
    border-top: 1px solid #f0f0f0;
    display: flex;
    gap: 12px;
    background: #fff;

    /* 固定在底部，不随树滚动 */
}
.group-tree-actions .ant-btn {
    flex: 1;
}
</style>
